package com.serookie.controller;

import com.serookie.dto.SysUserLoginParam;
import com.serookie.entity.Result;
import com.serookie.entity.SysUser;
import com.serookie.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
/**
 * @author kevintam
 * @version 1.0
 * @date 2021/5/6 20:30
 */
@RestController
@Api(value="SysUser登录接口",tags={"登录接口"})
public class SysUserLoginController{

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/doLogin")
    public Result login(@RequestBody SysUserLoginParam loginParam, HttpServletRequest request){
        System.out.println(loginParam.getUsername());
        return sysUserService.login(loginParam.getUsername(),loginParam.getPassword(),request);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok().message("退出成功");
    }

    @ApiOperation(value = "获取当前信息")
    @GetMapping("/admin/info")
    public Result info(Principal principal){
        if(principal==null){
            return null;
        }
        String username = principal.getName();
        SysUser admin=sysUserService.getSysUserByUsername(username);
        admin.setPassword(null);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        WebAuthenticationDetails details =(WebAuthenticationDetails) authentication.getDetails();
        return Result.ok().message("访问成功").data("admin", admin).data("details",details);
    }
    @GetMapping("/count")
    @ApiOperation("查询所有的用户数")
    public Result count(){
        Integer integer = sysUserService.goodsCount();
        return Result.ok().message("操作成功").data("count",integer);
    }
    @GetMapping("/maleCount")
    @ApiModelProperty("查询的所有的男生人数")
    public Result maleCount(){
        Integer integer = sysUserService.maleCount();
        return Result.ok().message("操作成功").data("maleCount",integer);
    }
}
